import React, { useState, useEffect, useMemo } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Modal, Button } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { reqWeather, CityInfo } from '../../api/index';
import menuConfig, { ISearchMenu } from '../../config/menu_config';
import dateUtils from '../../utils/date';
import userUnit from '../../utils/memory_utils';
import userStore from '../../utils/storage_utils';
import './index.less';

type LocationConfig = {
    pathname: string;
};
type PathItem = ISearchMenu | undefined;

const Header: React.FC = () => {
    const [currentTime, setCurrentTime] = useState<string>(dateUtils());
    const [{ city, weather, img2 }, setWeather] = useState<CityInfo>({
        city: '',
        weather: '',
        img2: ''
    });
    const navigate = useNavigate();
    const { pathname }: LocationConfig = useLocation();
    const pathName: string = useMemo(
        () => {
            let pathName: string = pathname.replace(/^\/admin\/|(?<=product)\/.+$/g, '');
            const pathItem: PathItem = menuConfig.find(({ key }: ISearchMenu) => key === pathName);
            pathName = pathItem?.title ?? '';
            return pathName;
        },
        [pathname]
    );
    const handleLogout = (): void => {
        Modal.confirm({
            icon: <ExclamationCircleOutlined />,
            content: '确定退出吗？',
            okText: '确认',
            cancelText: '取消',
            onOk() {
                userStore.removeUser();
                userUnit.isNotLogin = true;
                navigate('/login');
            }
        });
    };
    useEffect(() => {
        reqWeather().then(({ city, weather, img2 }: CityInfo): void => {
            setWeather({
                city, weather, img2
            });
        });
        const timer: NodeJS.Timer = setInterval(() => {
            setCurrentTime(dateUtils());
        }, 1000);
        return () => {
            clearInterval(timer);
        };
    }, []);
    return (
        <div className="header">
            <div className="header-top">
                <span>欢迎，{userUnit.user?.username ?? 'admin123'}</span>
                <Button type="link" onClick={handleLogout}>退出</Button>
            </div>
            <div className="header-bottom">
                <div className="header-bottom-left">{pathName}</div>
                <div className="header-bottom-right">
                    <span>{currentTime}</span>
                    &nbsp;
                    <span>{city}</span>
                    {img2 && <img src={`http://www.weather.com.cn/m/i/weatherpic/29x20/${img2}`} alt="weather" />}
                    <span>{weather}</span>
                </div>
            </div>
        </div>
    );
};

export default Header;